// eee.Sheffield.PZ.Imaging
//
// Copyright ?Ping Zou, 2007
// sg71.cherub@gmail.com

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using eee.Sheffield.PZ.Math;

namespace eee.Sheffield.PZ.Imaging.ImageFilter
{
    // Zou&Rocket 2007
    public class ZouModel
    {
        public int Zou(PZScanline sl,
            out double radius, out double centre, out double leftEdge, out double rightEdge)
        {
            int failCount = 0;
            sl.InvertProfile();
            int width = sl._widthOfScanline;

            radius = sl._r;
            centre = sl._c;
            leftEdge = centre - radius;
            rightEdge = centre + radius;
            try
            {
                sl.NMMin();

                // detect lack-of-fit
                if (sl.IsFit())
                {
                    // output
                    radius = sl._r;
                    centre = sl._c;
                    leftEdge = centre - radius;
                    rightEdge = centre + radius;
                }
            }
            catch (ApplicationException e)
            {
                // output
                System.Diagnostics.Debug.WriteLine(e.Message);
                failCount++;
            }
            return failCount;
        } // Zou()

        public int ZouRecord(PZScanline sl, string fileName)
        {

            FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream);

            int failCount = 0;
            sl.InvertProfile();
            int width = sl._widthOfScanline;

            //radius = sl.r;
            //centre = sl.c;
            //leftEdge = centre - radius;
            //rightEdge = centre + radius;
            try
            {
                sl.NMMin();
                sl.CalculateMin();
                sl.InvertProfile();
                // write fitted profile
                for (int i = 0; i < width; i++)
                {
                    writer.WriteLine(String.Format("{0, -10:f}", 255 - sl._ffit[i]));
                }
                writer.WriteLine();
                // detect lack-of-fit
                if (sl.IsFit())
                {
                    //// output
                    //radius = sl.r;
                    //centre = sl.c;
                    //leftEdge = centre - radius;
                    //rightEdge = centre + radius;
                }
            }
            catch (ApplicationException e)
            {
                // output
                System.Diagnostics.Debug.WriteLine(e.Message);
                failCount++;
            }

            writer.Flush();
            writer.Close();
            stream.Close();
            return failCount;
        } // ZouRecord()
    }
}
